package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.core.internal.Function;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CacheClient {

    private StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate=stringRedisTemplate;
    }

    public  void set(String key , Object value , Long time, TimeUnit unit){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,unit);
    }
    public  void setWithLogical(String key , Object value , Long time, TimeUnit unit) throws InterruptedException {
        com.hmdp.entity.RedisData redisData = new com.hmdp.entity.RedisData();
        Thread.sleep(50);
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R ,ID> R queryWithPassThrough(String keyPrefix, ID id , Class<R> type, Function<ID, R> dbFallback,Long time, TimeUnit unit){
        String key= keyPrefix+id;//long能直接加在string上？

        //查询redis是否存在
        String json = stringRedisTemplate.opsForValue().get(key);

        //存在返回
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        if(json !=null ){
            return null;
        }
        //不存在查数据库
        R r = dbFallback.apply(id);

        //数据库不存在报错
        if(r == null){
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //写入缓存
        String jsonStr = JSONUtil.toJsonStr(r);

        this.set(key,jsonStr,time,unit);
        //返回
        return r;
    }
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public <R,ID> R quertWithLogicalExpire(String keyPrefix,ID id,Class<R> type ,Function<ID,R> dbFallback,Long time, TimeUnit unit){

        String key= keyPrefix+id;//long能直接加在string上？

        //查询redis是否存在
        String json = stringRedisTemplate.opsForValue().get(key);

        //存在返回，防止缓存穿透
        if(StrUtil.isBlank(json)){
            return null;
        }

        //redis反序列化
        com.hmdp.entity.RedisData redisData = JSONUtil.toBean(json, com.hmdp.entity.RedisData.class);

        JSONObject data = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(data, type);
        //判断过期时间

        LocalDateTime expirTime = redisData.getExpireTime();
        //未过期返回

        //已过期
        if(expirTime.isAfter(LocalDateTime.now())){

            return r;
        }


        //缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY+id;

        //获取互斥锁
        boolean isLock = tryLock(lockKey);

        if(isLock){
            //开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R r1 = dbFallback.apply(id);
                    this.setWithLogical(key,r1,time,unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }

            });
        }
        //返回
        return r;
    }
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1",10,TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
}
